package com.neusoft.nep.SystemAdminstrator.Controller;

import com.neusoft.nep.SystemAdminstrator.Common.FileUtills;
import com.neusoft.nep.entity.GirdFeedback;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;

public class Othertotalstatis {
    @FXML
    private Button btn_out;
    @FXML
    private Button refreshBtn;
    @FXML
    private Label totalCountLabel;       // 空气质量检测总数量
    @FXML
    private Label goodCountLabel;        // 空气质量检测良好数量
    @FXML
    private Label overlimitCountLabel;   // 空气质量检测超标数量
    @FXML
    private Label provinceCoverageLabel; // 省网格覆盖范围
    @FXML
    private Label cityCoverageLabel;     // 大城市网格覆盖范围
    @FXML
    private Button btn_back;
    @FXML
    private MenuItem mi_PSL, mi_AQI, mi_PGC, mi_AqiDistribute, mi_Other, mi_AqiTrendTotal;

    // 中国省份总数（34个）和大城市数量（106个）
    private static final int TOTAL_PROVINCES = 34;
    private static final int TOTAL_BIG_CITIES = 106;

    @FXML
    public void initialize() {
        loadStatisticsData();
    }

    @FXML
    public void updateStatistics(ActionEvent event) {
        loadStatisticsData();
    }

    /**
     * 加载统计数据（核心方法）
     */
    private void loadStatisticsData() {
        // 初始化计数器和集合
        int totalCount = 0;              // 总数量
        int goodCount = 0;               // 良好数量（一级、二级）
        int overlimitCount = 0;          // 超标数量（三级~六级）
        Set<String> provinces = new HashSet<>();  // 不重复省份集合
        Set<String> bigCities = new HashSet<>();   // 不重复大城市集合

        try {
            // 1. 获取所有网格员文件名
            List<String> officerFiles = getOfficerFileNames();

            // 2. 遍历每个网格员文件
            for (String fileName : officerFiles) {
                if (fileName.endsWith("back.txt")) {
                    // 读取文件中的反馈数据（Map结构）
                    Map<String, GirdFeedback> feedbackMap = (Map<String, GirdFeedback>)
                            FileUtills.readMapObject(fileName);

                    if (feedbackMap != null) {
                        totalCount += feedbackMap.size(); // 累加总数量

                        // 遍历每条反馈数据
                        for (GirdFeedback feedback : feedbackMap.values()) {
                            if (feedback != null) {
                                // 统计良好/超标数量（整合GirdOfficerFeedBackInfoViewController的等级逻辑）
                                String level = getFinalLevel(feedback);
                                if (level != null) {
                                    if (level.equals("一级") || level.equals("二级")) {
                                        goodCount++;
                                    } else {
                                        overlimitCount++;
                                    }
                                }

                                // 统计省份和城市覆盖
                                String province = feedback.getProvince();
                                String city = feedback.getCity();
                                if (province != null && !province.isEmpty()) {
                                    provinces.add(province);
                                }
                                if (city != null && !city.isEmpty()) {
                                    bigCities.add(city);
                                }
                            }
                        }
                    }
                }
            }

            // 3. 计算覆盖百分比（保留整数）
            double provinceCoverage = provinces.isEmpty() ?
                    0 : (double) provinces.size() / TOTAL_PROVINCES * 100;
            double cityCoverage = bigCities.isEmpty() ?
                    0 : (double) bigCities.size() / TOTAL_BIG_CITIES * 100;

            // 4. 更新UI
            updateUI(totalCount, goodCount, overlimitCount,
                    (int) Math.round(provinceCoverage), (int) Math.round(cityCoverage));

        } catch (Exception e) {
            // 异常处理，显示默认值
            totalCountLabel.setText("0");
            goodCountLabel.setText("0");
            overlimitCountLabel.setText("0");
            provinceCoverageLabel.setText("0");
            cityCoverageLabel.setText("0");
            e.printStackTrace();
        }
    }

    /**
     * 获取GirdFeedback的最终等级（整合GirdOfficerFeedBackInfoViewController的等级计算逻辑）
     */
    private String getFinalLevel(GirdFeedback feedback) {
        try {
            // 解析污染物浓度
            double so2 = Double.parseDouble(feedback.getSO2());
            double co = Double.parseDouble(feedback.getCO());
            double pm25 = Double.parseDouble(feedback.getPM());

            // 计算各污染物等级
            int so2Level = getAqiLevel(so2, "SO2");
            int coLevel = getAqiLevel(co, "CO");
            int pm25Level = getAqiLevel(pm25, "PM2.5");

            // 取最大等级并转换为文本
            int finalLevel = Math.max(Math.max(so2Level, coLevel), pm25Level);
            return getLevelName(finalLevel);
        } catch (NumberFormatException e) {
            // 浓度解析失败时，返回反馈中已有的level（若存在）
            return feedback.getLevel();
        }
    }

    /**
     * 获取污染物对应的AQI等级（整合GirdOfficerFeedBackInfoViewController的逻辑）
     */
    private int getAqiLevel(double concentration, String pollutantType) {
        if ("SO2".equals(pollutantType)) {
            return getLevelByRange(concentration, 50, 150, 475, 800, 1600);
        } else if ("CO".equals(pollutantType)) {
            return getLevelByRange(concentration, 5, 10, 35, 60, 90);
        } else if ("PM2.5".equals(pollutantType)) {
            return getLevelByRange(concentration, 35, 75, 115, 150, 250);
        }
        return -1; // 异常情况
    }

    /**
     * 通用等级计算方法（整合GirdOfficerFeedBackInfoViewController的逻辑）
     */
    private int getLevelByRange(double concentration, double r1, double r2, double r3, double r4, double r5) {
        if (concentration >= 0 && concentration <= r1) return 1;
        else if (concentration > r1 && concentration <= r2) return 2;
        else if (concentration > r2 && concentration <= r3) return 3;
        else if (concentration > r3 && concentration <= r4) return 4;
        else if (concentration > r4 && concentration <= r5) return 5;
        else if (concentration > r5) return 6;
        return -1;
    }

    /**
     * 获取等级名称（整合GirdOfficerFeedBackInfoViewController的逻辑）
     */
    private String getLevelName(int level) {
        switch (level) {
            case 1: return "一级";
            case 2: return "二级";
            case 3: return "三级";
            case 4: return "四级";
            case 5: return "五级";
            case 6: return "六级";
            default: return "未知";
        }
    }

    /**
     * 获取所有网格员文件（girdxxxback.txt）
     */
    private List<String> getOfficerFileNames() {
        List<String> fileNames = new ArrayList<>();
        File directory = new File("."); // 当前工作目录
        File[] files = directory.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isFile() && file.getName().startsWith("gird") &&
                        file.getName().endsWith("back.txt")) {
                    fileNames.add(file.getName());
                }
            }
        }
        return fileNames;
    }

    /**
     * 更新UI显示
     */
    private void updateUI(int total, int good, int overlimit, int provincePerc, int cityPerc) {
        Platform.runLater(() -> {
            totalCountLabel.setText(String.valueOf(total));
            goodCountLabel.setText(String.valueOf(good));
            overlimitCountLabel.setText(String.valueOf(overlimit));
            provinceCoverageLabel.setText(String.valueOf(provincePerc));
            cityCoverageLabel.setText(String.valueOf(cityPerc));
        });
    }

    // 以下为界面跳转方法
    public void OUT(ActionEvent actionEvent) {
        System.exit(0);
    }

    public void PSLClick(ActionEvent event) throws IOException {
        loadFXML("../View/publicList.fxml");
    }

    public void AQIListClick(ActionEvent event) throws IOException {
        loadFXML("../View/AQImakesure.fxml");
    }

    public void PGCClick(ActionEvent event) throws IOException {
        loadFXML("../View/ProvincialGroupComponentItemInspectionStatistics.fxml");
    }

    public void AqiDistributeClick(ActionEvent event) throws IOException {
        loadFXML("../View/AqiDistributeTotalStatisView.fxml");
    }

    public void OtherClick(ActionEvent event) throws IOException {
        loadFXML("../View/OtherTotalStatisView.fxml");
    }

    public void AqiTrendClick(ActionEvent event) throws IOException {
        loadFXML("../View/AqiTrendTotalStatisView.fxml");
    }

    /**
     * 通用FXML加载方法
     */
    private void loadFXML(String fxmlPath) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource(fxmlPath);
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_out.getScene();
        scene.setRoot(root);
        Stage stage = (Stage) scene.getWindow();
        stage.show();
    }
}